<!--
 * @Descripttion: (关重件扫描验证关系/MES_SCAN_KEYS_RELATION)
 * @version: (1.0)
 * @Author: (liutao)
 * @Date: (2022-07-29)
 * @LastEditors: (liutao)
 * @LastEditTime: (2022-07-29)
-->
<template>
  <div>
    <!-- :model属性用于表单验证使用 比如下面的el-form-item 的 prop属性用于对表单值进行验证操作 -->
    <el-form
      :model="queryParams"
      size="small"
      label-position="right"
      inline
      ref="queryForm"
      v-show="showSearch"
      @submit.native.prevent
    >
      <!-- <el-form-item label="车型配置外键" prop="carTypeId">
        <el-input v-model.number="queryParams.carTypeId" placeholder="请输入车型配置外键" />
      </el-form-item> -->
      <el-form-item v-show="false">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          v-hasPermi="['business:mes_scan_keys_relation:add']"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          :disabled="single"
          v-hasPermi="['business:mes_scan_keys_relation:edit']"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          :disabled="multiple"
          v-hasPermi="['business:mes_scan_keys_relation:delete']"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:mes_scan_keys_relation:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 数据区域 -->
    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      highlight-current-row
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <!-- <el-table-column prop="keyId" label="关重件Id" align="center">
      </el-table-column> -->
      <el-table-column prop="materialCode" label="关重件编码" align="center">
      </el-table-column>
      <el-table-column prop="materialName" label="关重件名称" align="center">
      </el-table-column>
      <el-table-column prop="modelCode" label="产品型号" align="center">
      </el-table-column>
      <el-table-column prop="rulesCode" label="验证规则" align="center">
      </el-table-column>
      <el-table-column prop="stationCode" label="工位编码" align="center">
      </el-table-column>
      <el-table-column prop="materialCode" label="物料编码" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="materialName" label="物料名称" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="scanCode" label="扫描验证码" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="count" label="数量" align="center" />
      <el-table-column prop="lineCode" label="产线编码" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="writePlc" label="写入PLC" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['business:mes_scan_keys_relation:edit']"
            icon="el-icon-edit"
            style="margin-right: 9px"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['business:mes_scan_keys_relation:delete']"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      class="mt10"
      background
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改关重件扫描验证关系对话框 -->
    <el-dialog
      :title="title"
      :lock-scroll="false"
      :visible.sync="open"
      append-to-body
      width="760px"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-row :gutter="20">
          <el-col :lg="12" v-if="opertype == 2">
            <el-form-item label="主键">{{ form.id }}</el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="关重件" prop="keyId">
              <el-select
                v-model="form.keyId"
                placeholder="请选择关重件"
                style="width: 240px"
                filterable
                @change="ChangeKey"
              >
                <el-option
                  v-for="item in keyIdOptions"
                  :key="item.id"
                  :label="item.keyName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.keyCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.keyName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="验证规则" prop="rulesCode">
              <el-select v-model="form.rulesCode" placeholder="请选择验证规则" style="width: 240px">
                <el-option
                  v-for="item in rulesCodeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="工位编码" prop="stationCode">
              <el-select
                v-model="form.stationCode"
                placeholder="请选择工位编码"
                style="width: 240px"
                filterable
                @change="Change"
              >
                <el-option
                  v-for="item in stationCodeOptions"
                  :key="item.shopCode"
                  :label="item.shopName"
                  :value="item.shopCode"
                >
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.shopName }}</span>
                  <span style="float: left">{{ item.shopCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input
                v-model="form.materialCode"
                placeholder="请选择关重件获取物料编码"
                style="width: 240px"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input
                v-model="form.materialName"
                placeholder="请选择关重件获取物料名称"
                style="width: 240px"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="扫描验证码" prop="scanCode">
              <el-input
                v-model="form.scanCode"
                placeholder="请选择关重件获取扫描验证码"
                style="width: 240px"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="数量" prop="count">
              <el-input
                type="number"
                v-model="form.count"
                placeholder="请输入数量"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="产线编码" prop="lineCode">
              <el-input
                v-model="form.lineCode"
                placeholder="请输入工位编码"
                style="width: 240px"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="车型配置外键" prop="carTypeId" v-show="false">
              <el-input
                v-model="form.carTypeId"
                placeholder="请输入车型配置外键"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    listMESSCANKEYSRELATION,
    addMESSCANKEYSRELATION,
    delMESSCANKEYSRELATION,
    updateMESSCANKEYSRELATION,
    getMESSCANKEYSRELATION,
    exportMESSCANKEYSRELATION,
  } from "@/api/component/relation.js";
  import { listAllValidationrules } from "@/api/base/validationrules";
  import { GetALLlistCloseHeavyParts } from "@/api/base/keys";
  import { getShopByType, getShop } from "@/api/base/shop";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: "scanData",
    props: {
      clientId: {
        type: Number,
        default: 0,
      },
      cartypeInfo: {
        type: String,
        default: "",
      },
    },
    watch: {
      clientId: {
        handler(newVal, oldVal) {
          if (newVal) {
            this.queryParams.carTypeId = newVal;
            this.defaultcarTypeId = newVal;
            this.getList();
          }
        },
        immediate: true,
        deep: true,
      },
      cartypeInfo: {
        handler(newVal, oldVal) {
          if (newVal) {
            this.defaultcarTypeCode = newVal;
            var queryParams = {
              itemCode: newVal,
            };
            GetALLlistCloseHeavyParts(queryParams).then((res) => {
              this.keyIdOptions = res;
            });
          }
        },
        immediate: true,
        deep: true,
      },
    },
    data() {
      return {
        defaultcarTypeCode: "",
        defaultcarTypeId: 0,
        // 选中id数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sort: undefined,
          sortType: undefined,
          carTypeId: undefined,
        },
        // 弹出层标题
        title: "",
        // 操作类型 1、add 2、edit
        opertype: 0,
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        columns: [
          { index: 0, key: "id", label: `主键`, checked: true },
          { index: 1, key: "keyId", label: `关重件Id`, checked: true },
          { index: 2, key: "rulesCode", label: `验证规则`, checked: true },
          { index: 3, key: "stationCode", label: `工位编码`, checked: true },
          { index: 4, key: "materialCode", label: `物料编码`, checked: true },
          { index: 5, key: "materialName", label: `物料名称`, checked: true },
          { index: 6, key: "scanCode", label: `扫描验证码`, checked: true },
          { index: 7, key: "count", label: `数量`, checked: true },
          { index: 8, key: "lineCode", label: `产线编码`, checked: true },
          { index: 9, key: "writePlc", label: `写入PLC`, checked: false },
          { index: 10, key: "createTime", label: `创建时间`, checked: false },
          { index: 11, key: "delFlag", label: `删除标志`, checked: false },
          { index: 12, key: "updateBy", label: `更新标志`, checked: false },
          { index: 13, key: "updateTime", label: `更新时间`, checked: false },
          { index: 14, key: "createBy", label: `创建人`, checked: false },
          { index: 15, key: "fIELD1", label: `备用字段1`, checked: false },
          { index: 16, key: "fIELD2", label: `备用字段2`, checked: false },
          { index: 17, key: "fIELD3", label: `备用字段3`, checked: false },
          { index: 18, key: "fIELD4", label: `备用字段4`, checked: false },
          { index: 19, key: "carTypeId", label: `车型配置外键`, checked: false },
        ],
        // 关重件Id选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        keyIdOptions: [],
        // 验证规则选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        rulesCodeOptions: [],
        // 工位编码选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        stationCodeOptions: [],
        // 数据列表
        dataList: [],
        // 总记录数
        total: 0,
        // 提交按钮是否显示
        btnSubmitVisible: true,
        // 表单校验
        rules: {
          keyId: [
            { required: true, message: "关重件Id不能为空", trigger: "change" },
          ],
          stationCode: [
            { required: true, message: "工位编码不能为空", trigger: "change" },
          ],
          count: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        },
      };
    },
    created() {
      // 列表数据查询
      this.getList();
      // 列表数据查询
      var shoptype = "4";
      getShopByType(shoptype).then((res) => {
        this.stationCodeOptions = res.data;
      });
      listAllValidationrules().then((res) => {
        this.rulesCodeOptions = res;
      });
    },
    methods: {
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm(
          "是否确认导出产品为" + this.defaultcarTypeCode + "的所有关重件数据项?",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return exportMESSCANKEYSRELATION(queryParams);
          })
          .then((response) => {
            this.download(response.data.path);
          });
      },
      //下拉联动
      Change(e) {
        // 根据id进行筛选（id是唯一的，如果获取多个，需要自己重新定义筛选条件）
        let item = this.stationCodeOptions.filter((options) => {
          return options.shopCode === e;
        });
        console.log(item[0]);
        this.GetLine(item[0].parentId);
      },
      async GetLine(item) {
        await getShop(item).then((response) => {
          this.form.lineCode = response.data.shopCode;
        });
      },
      //下拉联动
      ChangeKey(e) {
        // 根据id进行筛选（id是唯一的，如果获取多个，需要自己重新定义筛选条件）
        let item = this.keyIdOptions.filter((options) => {
          return options.id === e;
        });
        this.form.materialCode = item[0].keyCode;
        this.form.materialName = item[0].keyName;
        this.form.scanCode = item[0].scanCode;
      },
      // 查询数据
      getList() {
        this.loading = true;
        listMESSCANKEYSRELATION(this.queryParams).then((res) => {
          if (res.code == 200) {
            this.dataList = res.rows;
            this.total = res.total;
            this.loading = false;
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 重置数据表单
      reset() {
        this.form = {
          keyId: undefined,
          rulesCode: undefined,
          stationCode: undefined,
          materialCode: undefined,
          materialName: undefined,
          scanCode: undefined,
          count: undefined,
          lineCode: undefined,
          writePlc: undefined,
          carTypeId: this.carTypeId,
        };
        this.resetForm("form");
      },
      // 重置查询操作
      resetQuery() {
        this.timeRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 自定义排序
      sortChange(column) {
        if (column.prop == null || column.order == null) {
          this.queryParams.sort = undefined;
          this.queryParams.sortType = undefined;
        } else {
          this.queryParams.sort = column.prop;
          this.queryParams.sortType = column.order;
        }

        this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加";
        this.opertype = 1;
        this.form.carTypeId = this.queryParams.carTypeId;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const Ids = row.id || this.ids;

        this.$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
          .then(function () {
            return delMESSCANKEYSRELATION(Ids);
          })
          .then(() => {
            this.handleQuery();
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getMESSCANKEYSRELATION(id).then((res) => {
          const { code, data } = res;
          if (code == 200) {
            this.open = true;
            this.title = "修改数据";
            this.opertype = 1;
            this.form.carTypeId = this.queryParams.carTypeId;
            this.form = {
              ...data,
            };
          }
        });
      },
      // 关重件Id字典翻译
      keyIdFormat(row, column) {
        return this.selectDictLabel(this.keyIdOptions, row.keyId);
      },
      // 验证规则字典翻译
      rulesCodeFormat(row, column) {
        return this.selectDictLabel(this.rulesCodeOptions, row.rulesCode);
      },

      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            console.log(JSON.stringify(this.form));

            if (this.form.id != undefined && this.opertype === 1) {
              updateMESSCANKEYSRELATION(this.form)
                .then((res) => {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                })
                .catch((err) => {
                  //TODO 错误逻辑
                });
            } else {
              addMESSCANKEYSRELATION(this.form)
                .then((res) => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                })
                .catch((err) => {
                  //TODO 错误逻辑
                });
            }
          }
        });
      },
    },
  };
</script>